package com.gayworld.ws.user;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gayworld.model.entity.qb.QBSession;
import com.gayworld.ws.authentication.Credentials;
import com.gayworld.ws.common.WSConstants;
@Service
public class QBSessionServiceImpl implements QBSessionService{

	private final Logger logger = LogManager.getLogger(this.getClass()
			.getName());

	// new User("tester2","Jopancho2")
	public QBSession getSession(String login, String password) throws Exception {
		QBSession qbSession = null;

		long timestamp = System.currentTimeMillis() / 1000;
		int nonce = new Random().nextInt();
		String signatureParams = String.format(WSConstants.login_param_format,
				Credentials.qbAppId, Credentials.qbAuthorizationKey, nonce,
				timestamp, login, password);

		// create entity
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("application_id",
				Credentials.qbAppId));
		formparams.add(new BasicNameValuePair("auth_key",
				Credentials.qbAuthorizationKey));
		formparams.add(new BasicNameValuePair("nonce", String.valueOf(nonce)));
		formparams.add(new BasicNameValuePair("timestamp", String
				.valueOf(timestamp)));
		formparams.add(new BasicNameValuePair("user[login]", login));
		formparams.add(new BasicNameValuePair("user[password]", password));
		formparams.add(new BasicNameValuePair("signature", Credentials
				.getSignature(signatureParams)));

		UrlEncodedFormEntity postEntity = null;
		try {
			postEntity = new UrlEncodedFormEntity(formparams, "UTF-8");

			// postEntity.setContentType("application/json");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}

		HttpClient client = HttpClientBuilder.create().build();
		HttpPost post = new HttpPost(WSConstants.QB_URL_AUTHENTICATION);
		post.setEntity(postEntity);

		HttpResponse response;

		try {

			response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
 			String line = rd.readLine();
			 
			logger.debug("respuesta -> " + line);	
		 
			  qbSession = new ObjectMapper().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")).readValue(line, QBSession.class);
		logger.debug("id -> " + qbSession.getSession().get_id());	

		} catch (IOException e) {
			logger.error("IOException -> " + e.getMessage());
			// TODO Auto-generated catch block
			// e.printStackTrace();
		} catch (Exception e) {
			logger.error("Exception Error -> " + e.getMessage());
			e.printStackTrace();
		}
		return qbSession;
	}

}
